Storing Database Connection Strings in App.Config
.NET Framework 2.0 added a separate configuration section in both Windows Application configuration (App.config) and Web Application configuration (Web.config) file. Developers can use these section to store connection string information such as a connection string name or provider type etc. In the following tutorial I will show you how you can store and retrieve connection string information in .NET Windows Application using VB.Net.
The following code shows how you can store connection strings in App.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="name" value="provider=microsoft.jet.oledb.4.0;data source=E://invent.mdb"/>
</appSettings>
</configuration>
In the code behind you should import the following namespace:
Imports System.Configuration
Then retreive the value from the App.Config by the following code
Dim con As String = ConfigurationSettings.AppSettings("name").ToString()
Example
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.Configuration
Imports System.Data.OleDb
Public Class Form1
Dim con As String = ConfigurationSettings.AppSettings("name").ToString()
Dim mycon As OleDbConnection
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
mycon = New OleDbConnection(con)
mycon.Open()
Dim cmd1 As New OleDbCommand("select location from purchasing ", mycon)
Dim dr As OleDbDataReader = cmd1.ExecuteReader()
While dr.Read()
textBox1.Text = dr(0).ToString()
End While
mycon.Close()
End Sub
End Class